from new_auth import db
from fastapi_jwt_auth import AuthJWT
from fastapi import Request, HTTPException
from common.third_party.dkg import validate
from common.third_party.save_config import load_config, save_config
from settings import settings


def server_auth(token: str) -> bool:
    prev = load_config('auth/prev_timestamp', float, 0.0)
    valid, timestamp = validate('zxc1000-7', prev, token)
    if valid:
        save_config('auth/prev_timestamp', timestamp)

    return valid


async def auth(authorize: AuthJWT, request: Request) -> (bool, str):
    try:
        if server_auth(authorize._token):
            return False, 'server'

        if settings.AUTH_WHITE_LIST and request.client.host in ['10.16.0.222', '10.16.0.140', '10.16.0.90', '10.16.0.142', '10.16.0.144', '10.16.0.181', '10.16.0.110']:
            return True, 'adjuster'

        authorize.jwt_required()
        username = authorize.get_jwt_subject()
        user_role = db.get_user_role(username)
        return True, user_role
    except Exception as e:
        raise HTTPException(status_code=401, detail=str(e))
